import { Formik, Form, Field, ErrorMessage, useField } from 'formik'
import * as Yup from 'yup'

function App() {
  const initialValues = { username: '', password: '', subject: '', description: '', checkeds: ['篮球'] }
  const handleSubmit = values => {
    console.log(values)
  }
  const schema = Yup.object({
    username: Yup.string().max(5, '用户名超长').required('请输入用户名'),
    password: Yup.string().max(10, '密码超长').required('请输入密码'),
    subject: Yup.string().required('请选择主题'),
    description: Yup.string().required('请输入描述')
  })
  return (
    <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={schema}>
      <Form>
        <div>
          <Field name="username"></Field>
          <ErrorMessage name="username"></ErrorMessage>
        </div>
        <div>
          {/* <Field name="password"></Field> */}
          <MyPassword
            label="密码"
            name="password"
            id="password"
            placehloder="请输入密码"
          ></MyPassword>
        </div>
        <div>
          <Field name="description"></Field>
          <ErrorMessage name="description"></ErrorMessage>
        </div>
        <div>
          <Field name="subject" as="select">
            <option value="前端">前端</option>
            <option value="JAVA">JAVA</option>
          </Field>
          <ErrorMessage name="subject"></ErrorMessage>
        </div>
        <div>
          <Checked label="篮球" value="篮球" name="checkeds"></Checked>
          <Checked label="足球" value="足球" name="checkeds"></Checked>
          <Checked label="排球" value="排球" name="checkeds"></Checked>
        </div>
        <input type="submit"></input>
      </Form>
    </Formik>
  )
}

function MyPassword({ label, ...props }) {
  const [field, meta] = useField(props)
  return (
    <div>
      <label htmlFor={props.id}>{label}</label>
      <input {...field} {...props}></input>
      {meta.touched && meta.error ? <span>{meta.error}</span> : null}
    </div>
  )
}

function Checked({ label, ...props }) {
  const [field, meta, checkeds] = useField(props)
  const { value } = meta
  const { setValue } = checkeds
  const handleChange = () => {
    const set = new Set(value)
    if (set.has(props.value)) {
      set.delete(props.value)
    } else {
      set.add(props.value)
    }
    setValue([...set])
  }
  return (
    <div>
      <label htmlFor="">
        <input checked={value.includes(props.value)} type="checkbox" {...props} onChange={handleChange}></input>
        {label}
      </label>
    </div>
  )
}

export default App
